#include <sys/socket.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <signal.h>
#include <arpa/inet.h>
#include <unistd.h>

#define MAX_BUFF 100

int conn_fd;

void exit_client()
{
  printf("已退出！\n");
  close(conn_fd);
  exit(0);
}

int main(int argc, char *argv[])
{
  int server_port;
  struct sockaddr_in server_addr;
  char send_buff[MAX_BUFF];
  char recv_buff[MAX_BUFF];
  char c;
  int i;

  if (argc != 3) {
    printf("参数错误\n");
    return 1;
  }

  if ((conn_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    perror("创建套接字失败");
    return 1;
  }

  // 处理服务器地址
  memset(&server_addr, 0, sizeof(struct sockaddr_in));
  server_addr.sin_family = AF_INET;
  server_port = atoi(argv[2]);
  if (server_port < 0 || server_port > 65535) {
    printf("端口错误！\n");
    return 1;
  }
  server_addr.sin_port = htons(server_port);
  if (inet_aton(argv[1], &server_addr.sin_addr) == 0) {
    printf("ip地址错误\n");
    return 1;
  }

  if (connect(conn_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in)) < 0) {
    perror("连接失败");
    return 1;
  }

  signal(SIGINT, exit_client);

  while (1) {
    printf("请输入要发送的内容：");

    i = 0;
    while ((c = getchar()) != '\n' && c != EOF) {
      send_buff[i++] = c;
    }
    send_buff[i] = '\0';

    if (send(conn_fd, send_buff, sizeof(send_buff), 0) < 0) {
      perror("发送失败");
      return 1;
    }

    if (recv(conn_fd, recv_buff, sizeof(recv_buff), 0) < 0) {
      perror("接收失败");
      return 1;
    }else {
      printf("接收信息：%s\n", recv_buff);
    }
  }

  return EXIT_SUCCESS;
}
